package com.stop.think.service;

import com.stop.think.dao.MemberDao;
import com.stop.think.dao.entity.Member;
import com.stop.think.dao.entity.SendSmsMsgError;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author zhaolipeng
 */
@Slf4j
@Service
public class AsyncBetterThinkService {

  @Resource private MemberDao memberDao;
  @Resource private HttpSendSmsMessage httpSendSmsMessage;

  private int retry = 5;

  @Async
  public void sendSmsMessage(String shopId, CountDownLatch latch) {
    String telNums = memberDao
        .findByShopId(shopId)
        .stream()
        .map(Member::getTelNum)
        .collect(Collectors.joining(","));
    try {
      httpSendSmsMessage.batchSendMessage("祝你生日快乐！", telNums);
    } catch (Exception e) {
      log.error("发送短信错误", e);
    }
    latch.countDown();
  }

  @Async
  public void errorRetrySendSmsMessage(String shopId, CountDownLatch latch) {
    String telNums = memberDao
        .findByShopId(shopId)
        .stream()
        .map(Member::getTelNum)
        .collect(Collectors.joining(","));
    // 每个线程独立重试次数
    int selfRetry = retry;
    boolean successRetry = false;
    while (selfRetry > 0) {
      try {
        httpSendSmsMessage.batchSendMessage("祝你生日快乐！", telNums);
        // 发送成功后，直接终止重试
        selfRetry = 0;
        successRetry = true;
      } catch (Exception e) {
        log.error("发送短信错误", e);
      }
      if (selfRetry > 0) {
        try {
          // 一般发生的错误都会是网络波动，所以先等待两秒后再重试
          Thread.sleep(TimeUnit.SECONDS.toMillis(2));
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        selfRetry--;
      }
    }
    if (!successRetry) {
      // 保存错误信息
      SendSmsMsgError error = new SendSmsMsgError();
      error.setReason("xxxx");
      error.setShopId(shopId);
    }
    latch.countDown();
  }
}
